<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Cache;
use think\facade\Event;

class Product extends Base
{
    protected $name = 'product';

    public function cate1()
    {
        return $this->hasOne(ProductCate::class, 'id', 'cate_1')->field('id,title');
    }

    public function cate2()
    {
        return $this->hasOne(ProductCate::class, 'id', 'cate_2')->field('id,title');
    }

    public function cate3()
    {
        return $this->hasOne(ProductCate::class, 'id', 'cate_3')->field('id,title');
    }

    public function discount()
    {
        return $this->hasOne(Product::class, 'id', 'give_discount_pid')->field('id,title,vip_price,icon');
    }

    public function business()
    {
        return $this->hasOne(Business::class, 'id', 'business_id')
            ->field('id,title,logo,mobile,customer_tel,full_address,fans,contacts,describe_score,logistics_score,service_score');
    }

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,nickname,real_name,mobile,level_id,level_bonus_id,level_video_id,agent_level,syn_level,province,city,district');
    }

    public function getExamineStatusTextAttr($value, $data)
    {
        switch ($data['examine_status']) {
            case 1:
                return "待审核";
            case 2:
                return "已通过";
            case 3:
                return "已驳回";
            default:
                return "未知";
        }
    }

    public function getExamineTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '';
    }

    public function getImagesAttr($value)
    {
        return $value ? explode(',', $value) : [];
    }

    public function getContentImagesAttr($value)
    {
        return $value ? explode(',', $value) : [];
    }


    public static function _save($param, $business = '')
    {
        return self::_saveSpec($param);
    }


    public static function saveProduct($param)
    {
        parent::startTrans();
        try {
            $specData = $param['specData'];
            $skus = $param['skus'];
            $images=explode(',', $param['images']);
            $param['icon'] = isset($param['images']) ? $images[0] : '';
            $param['images'] = !empty($param['images']) ? $param['images'] : '';
            $param['content_images'] = !empty($param['content_images']) ? $param['content_images'] : '';
            
            //$param['service'] = !empty($param['service']) ? implode(',', $param['service']) : '';
            unset($param['specData']);
            unset($param['skus']);
            unset($param['file']);
            if (isset($param['id']) && $param['id']) {
                $info =parent::find($param['id']);
                $param['content_text'] = !empty($param['content_text']) ? $param['content_text'] : $info->content_text;
                $product = parent::update($param);
                $product->operation = 'save';
                //监听无效商品
                Event::trigger('InvalidProductCart', ['pid' => $param['id']]);
            } else {
                $product = parent::create($param);
                $product->operation = 'create';
            }

            //设置商品规格数据
            $result = ProductSpecData::setSpecData($product->id, $specData);
            if (!$result) {
                parent::rollback();
                return ['code' => -1, 'msg' => '加载失败，error:1'];
            }

            //设置商品规格值
            $result = ProductSpecValue::setSpecValue($product->id, $skus);
            if (!$result) {
                parent::rollback();
                return ['code' => -1, 'msg' => '加载失败，error:2'];
            }
            foreach ($result as $k => $v) {
                $product->$k = $v;
            }
            $product->save();

            parent::commit();
            // if ($business) {
            //     return ['code' => 1, 'msg' => $msg];
            // } else {
                Event::trigger('Logs', $product);
                return ['code' => 1, 'msg' => '已保存'];
            // }

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function recordLog($model)
    {

        $emp_id = session('admin_id');
        $emp_name = Admin::where('id', $emp_id)->value('admin_name');
        $title = '商品';
        $operation = getOperation($model->operation);
        if (in_array($model->operation, ['updateAll', 'deleteAll'])) {
            $msg = $operation . '【' . $title . '】' . '标识ID【' . implode(',', $model->ids) . '】';
            Logs::adds($msg, $emp_id, $emp_name);
        } else {
            $msg = $operation . '【' . $title . '】' . '标识ID【' . $model->id . '】标题【' . $model->title . '】';
            Logs::adds($msg, $emp_id, $emp_name);
        }
    }


    public static function submit($param, $user): array
    {
        try {
            $all = [];
            $info = parent::where(['id' => $param['id'], 'is_del' => 0, 'status' => 1])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '商品不存在或已下架'];
            }
            if (!$param['price'] || $param['price'] <= 0) {
                return ['code' => -1, 'msg' => '商品价格错误'];
            }
            if ($info->stock == 0) {
                return ['code' => -1, 'msg' => '库存不足！'];
            }
            
            if(isset($param['shoptype']) && !empty($param['shoptype'])){
                $shoptype=$param['shoptype'];
            }else{
                $shoptype='shop';
            }
            if(isset($param['seckill_id']) && !empty($param['seckill_id'])){
                $seckill_id=$param['seckill_id'];
            }else{
                $seckill_id=0;
            }
            $all[] = [
                'pid'    => $info->id,
                'num'    => $param['num'],
                'types'    => $param['types'],
                'spec' => $param['spce'],
                'price' => $param['price'],
                'shoptype' => $shoptype,
                'seckill_id' => $seckill_id,
                'cate_1' => $info->cate_1,
            ];

            Cache::set('tsOrder_' . $user->id, json_encode($all));

            return ['code' => 1, 'msg' => '选择商品成功！'];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    public function getIsAuditAttr($value)
    {
        switch ($value) {
            case 1:
                return '待审核';
            case 2:
                return '已通过';
            case 3:
                return '已驳回';
            default:
                return '未知';
        }
    }

    public static function examineSave($param, $admin)
    {
        $info = parent::where('id', $param['id'])->find();
        if (empty($info)) {
            return ['code' => -1, 'msg' => '商品不存在'];
        }
        if ($info->examine_status != 1) {
            return ['code' => -1, 'msg' => '该商品已审核'];
        }
        if (!$param['type']) {
            return ['code' => -1, 'msg' => '请选择要审核的操作'];
        }
        if ($param['type'] == 3 && !$param['examine_msg']) {
            return ['code' => -1, 'msg' => '请填写驳回原因'];
        }
        parent::startTrans();
        try {
            $info->examine_status = $param['type'];
            $info->examine_time = time();
            $info->examine_msg = isset($param['examine_msg']) ? $param['examine_msg'] : '';
            $info->examine_admin_id = $admin->id;
            $info->examine_admin_name = $admin->admin_name;
            $info->save();

//            $res = self::_saveSpec($param);
//            if ($res['code'] != 1) {
//                parent::rollback();
//                return ['code' => -1, 'msg' => '审核失败：' . $res['msg']];
//            }
            parent::commit();
            return ['code' => 1, 'msg' => '已审核'];

        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
